<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn Blog:http://blog.sina.com.cn/saverneo     |
// +------------------------------------------------------------------------+
//
/**
 * 回车
 */

namespace AuctionBack\Controller;

use AuctionBack\Logic\ProceduresRequirementLogic;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\Common\AjaxPage;
use AuctionCore\AuctionOrder\CarReturn;
use AuctionCore\Other\Store;
use AuctionCore\AuctionOrder\Recheck;
use AuctionCore\Account\Back\Employee;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\System\SystemConf;

class CarReturnController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
//        $order_pay_status = C('ORDER_PAY_STATUS');
//        unset($order_pay_status[0]);
//        $this->order_pay_status = $order_pay_status;
//        $this->assign('order_pay_status',$this->order_pay_status);
    }

    //待回车
    public function index()
    {
        $this->display();
    }

    //回车中
    public function returning()
    {
        $store = new Store();
        $map = ['status' => 0];
        if ($this->is_hq == false) {
            $map['city'] = ['in', $this->user_info['bc_code']];
        }
        $stores = $store->get_stores($map);
        $this->assign('stores', $stores);
        $this->display();
    }

    //已到店
    public function arrival()
    {
        $store = new Store();
        $map = ['status' => 0];
        if ($this->is_hq == false) {
            $map['city'] = ['in', $this->user_info['bc_code']];
        }
        $stores = $store->get_stores($map);
        $this->assign('stores', $stores);
        $this->display();
    }

    public function returning_list()
    {
        $page = I("get.p/d", 1);
        $limit = 10;
        $location_area = I('get.location_area', 0);
        if ($location_area == 0) {
            $location_area = $this->user_info['bc_code'];
        } else {
            $location_area = [$location_area];
        }
        $order_no = I("get.order_num", '');
        $checker = I("get.checker", '');
        $driver = I("get.driver", '');
        $driver_phone = I("get.driver_phone", '');
        $delive_store = I("get.delive_store", '');
        $pay_status = I('get.pay_status/d', 0);
        $status = I('get.status/d', 0);
        $start_time = I('get.start_time', '');
        $end_time = I('get.end_time', '');
        //权限验证
        $auth = false;
        $action_auth = false;
        $e = new Employee($this->user_info['username']);
        if ($status == 0) {
            $rules = "DaiHuiCheChaKanSuoYou";
            $auth = $e->check_auth($rules);
            $action_auth = $e->check_auth("HuiCheCaoZuo");
        } elseif ($status == 1) {
            $rules = "HuiCheZhongChaKanSuoYou";
            $auth = $e->check_auth($rules);
            $action_auth = $e->check_auth("HuiCheZhongCaoZuo");
        } elseif ($status == 2) {
            $rules = "YiDaoDianChaKanSuoYou";
            $auth = $e->check_auth($rules);
            $action_auth = $e->check_auth("YiDaoDianCaoZuo");
        }
        $cr = new CarReturn();
        $result = $cr->get_list($page, $limit, $pay_status, $status, $location_area, $order_no, $checker, $driver, $driver_phone, $delive_store, $auth, $start_time, $end_time);
        $total = $result['total'] > 0 ? $result['total'] : 0;
        $list = $result['list'] > 0 ? $result['list'] : [];
        $Page = new AjaxPage($total, $limit, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $page_show = $Page->show();
        $this->assign('p', $page);
        $this->assign('location_area', $location_area);
        $this->assign("action_auth", $action_auth);
        $this->assign('status', $status);
        $this->assign('page', $page_show);
        $this->assign('list', $list);
        $this->display();
    }

    //回车信息
    public function car_return_detail()
    {
        //权限验证
        $e = new Employee($this->user_info['username']);
        $action_auth = $e->check_auth("HuiCheCaoZuo");
        if ($action_auth == false) {
            $this->helpJsRedirect("无权限");
        }
        $order_id = I("get.oid/d", 0);
        if ($order_id < 1) {
            $this->helpJsRedirect("参数不正确");
        }
        $o = new AuOrder($order_id);
        $detail = $o->get_return_detail();
        $store = new Store();
        $map = [];
        $map['status'] = 0;
        $map['type'] = 3;//交付店
        if ($this->is_hq == false) {
            $map['city'] = ['in', $this->user_info['bc_code']];
        }
        $stores = $store->get_stores($map);
        $this->assign('stores', $stores);
        $procedures = SystemConf::getConfValueByName("RETURN_PROCEDURES", 1);
        $this->assign('procedures', $procedures);
        $procedures_before = SystemConf::getConfValueByName("BEFORE_TRANSFER_PROCEDURES", 1);
        $procedures_after = SystemConf::getConfValueByName("AFTER_TRANSFER_PROCEDURES", 1);
        $this->assign('procedures_before', $procedures_before);
        $this->assign('procedures_after', $procedures_after);
        $this->assign('detail', $detail);
        $this->display();
    }

    public function commit_return()
    {
        $order_id = I('post.order_id');
        if ($order_id < 1) {
            $this->helpJsonResult(400, '参数不正确');
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        if (empty($order)) {
            $this->helpJsonResult("未找到订单信息");
        }
        $Car = new Car($order['car_id']);
        $carInfo = $Car->detail();
        if ($order['status'] != 8) {
            $this->helpJsonResult(500, "操作非法,请刷新重试或联系超级管理员");
        }
        //检查前置状态
        if ($order['return_check_status'] != 1) {
            $this->helpJsonResult(500, "操作非法,请刷新重试或联系超级管理员");
        }
        $delive_store = I('post.delive_store', 0);
        if ($delive_store == 0) {
            $this->helpJsonResult(400, "请选择交付门店");
        }
        $refuel_demand = I('post.refuel_demand', 0);
        $driver_company = I('post.driver_company', 0);
        $driver_name = I('post.driver_name', 0);
        $driver_phone = I('post.driver_phone', 0);
        if (!validatePhone($driver_phone)) {
            $this->helpJsonResult(400, "请输入正确的手机号码");
        }
        $depart_time = I('post.depart_time', 0);
        $procedure = I('post.procedure', 0);
        $carkey = I("post.carkey", 0);
        $invoice = I('post.invoice', 0);
        $procedures_upload = I('post.procedures_upload');
        $remark = I('post.remark', '');
        $data = [
            'delive_store' => $delive_store,
            'refuel_demand' => $refuel_demand,
            'driver_company' => $driver_company,
            'driver_name' => $driver_name,
            'driver_phone' => $driver_phone,
            'depart_time' => $depart_time,
            'procedure' => $procedure,
            'carkey' => $carkey,
            'invoice' => $invoice,
            'return_remark' => $remark,
            'status' => 1
        ];
        $orderData = ['return_check_status' => 2];
        $proceduresDataList = [];
        foreach ($procedures_upload as $key => $pv) {
            $proceduresDataList[$key] = $pv;
            $proceduresDataList[$key]['order_id'] = $order_id;
            $proceduresDataList[$key]['sid'] = $carInfo['sid'];
        }
        $prLogic = new ProceduresRequirementLogic($carInfo['sid']);
        //开启事务
        M()->startTrans();
        $cr = new CarReturn();
        $rs = $cr->update_by_order_id($order_id, $data);
        if(!$rs){
            M()->rollback();
            $this->helpJsonResult(500, "回车信息更新失败");
        }
        $orderRes = $o->update($orderData);
        if(!$orderRes){
            M()->rollback();
            $this->helpJsonResult(500, "拍单更新失败");
        }
        if(!empty($proceduresDataList)){
            $res = $prLogic->addDataList($proceduresDataList);
            if(!$res){
                M()->rollback();
                $this->helpJsonResult(500, "手续上传要求添加失败");
            }
        }
        M()->commit();
        //记录日志
        $this->record_log($order_id, $order['car_id'], "确认回车");
        $this->helpJsonResult(200, "success");
    }

    //到店信息
    public function arrival_detail()
    {
        $order_id = I("get.oid/d", 0);
        if ($order_id < 1) {
            $this->error("参数不正确");
        }
        $o = new AuOrder($order_id);
        $detail = $o->get_return_detail();
        if ($detail['return_check_status'] == 2) {
            $rules = "HuiCheZhongCaoZuo";
        } else {
            $rules = "YiDaoDianCaoZuo";
        }
        //权限验证
        $e = new Employee($this->user_info['username']);
        $action_auth = $e->check_auth($rules);
        if ($action_auth == false) {
            $this->error("无权限", U('/CarReturn/index'));
        }
        $return_detail = CarReturn::get_detail_by_order_id($order_id);
        $s = new Store();
        $store = $s->detail(['store_id' => $return_detail['delive_store']]);
        $return_detail['delive_store_str'] = $store['store_name'];
        $c = new Car($detail['car_id']);
        $desc = $c->detail('car_perform');
        $return_detail['desc'] = $desc['other_info'];

        //获取手续上传要求
        $prLogic = new ProceduresRequirementLogic($return_detail['sid']);
        $beforeTransfer = $prLogic->getListByTransferStatus(1);
        $afterTransfer = $prLogic->getListByTransferStatus(2);
        $this->assign('beforeTransfer', $beforeTransfer);
        $this->assign('afterTransfer', $afterTransfer);
        $this->assign('detail', $detail);
        $this->assign('return_detail', $return_detail);
        $this->display();
    }

    //确认到店
    public function confirm_arrive()
    {
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        $c = new Car($order['car_id']);
        $carInfo = $c->detail();
        if (empty($order)) {
            $this->helpJsonResult(400, "未找到订单信息");
        }
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        if ($order['status'] != 8) {
            $this->helpJsonResult(500, "操作非法,请刷新重试或联系超级管理员");
        }
        //检查前置状态
        if ($order['return_check_status'] != 2) {
            $this->helpJsonResult(500, "操作非法,请刷新重试或联系超级管理员");
        }
        $arrival_time = I('post.arrival_time', '');
        if (empty($arrival_time)) {
            $this->helpJsonResult(400, "请选择到店时间!");
        }
        $remark = I('post.remark');
        $data = [
            'arrival_time' => $arrival_time,
            'arrival_remark' => $remark,
            'status' => 2
        ];
        //开启事务
        M()->startTrans();
        $cr = new CarReturn();
        $rs = $cr->update_by_order_id($order_id, $data);
        $ors = $o->update(['return_check_status' => 3]);
        $rs1 = Recheck::create([
            'order_id' => $order_id,
            'sid' => $carInfo['sid'],
            'car_id' => $order['car_id'],
            'status' => 0]);
        if (!$rs || !$ors || !$rs1) {
            M()->rollback();
        }
        M()->commit();

        $this->record_log($order_id, $order['car_id'], "确认到店");
        $this->helpJsonResult(200, "success");
    }

    private function record_log($order_id, $car_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
    }

    //违约
    public function violate()
    {
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(400, "拍单已锁定");
        }
        $poInfo = $o->getPurchaseByOrderId();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $car_plate_number = C('PLATE_PREFIX')[$carInfo['plate_prefix']] . $carInfo['plate_suffix'];
        $data = [];
        $data['order_id'] = $order_id;
        $data['order_no'] = $orderInfo['order_no'];
        $data['po_id'] = $poInfo['id'];
        $data['po_no'] = $poInfo['purchase_order_nu'];
        $data['car_plate_number'] = $car_plate_number;
        $data['order_status'] = $orderInfo['status'];
        $data['source'] = 1;
        $data['originator'] = $this->emp_id;
        $res = ChangeOrder::CreateChangeOrder($data);
        if (!$res) {
            $this->helpJsonResult(400, '处理失败');
        } else {
            $this->record_log($order_id, $orderInfo['car_id'], "4S店回车发起违约");
            $this->helpJsonResult(200, '处理成功');
        }
    }
}
